package com.pajx.testopengles.views.two_d

import android.content.Context
import android.opengl.GLES20
import android.util.Log
import com.pajx.testopengles.util.ShaderHelper
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer

/**
 *User: RandBII
 *Date: 2020/8/10
 *Description:
 */
class Triangle(context: Context) {

    private var mContext: Context? = null

    init {
        mContext = context
    }

    private val COOR_PRE_VERTEX = 3
    var vertexBuffer: FloatBuffer? = null

    var vertexShaderCode =
        ShaderHelper.loadShaderAsserts(mContext!!,  "tri_vert.glsl")

    val fragmentShaderCode =
        ShaderHelper.loadShaderAsserts(mContext!!,  "tri_fag.glsl")

    var mProgram: Int? = null
    var mPositionHandle: Int = -1
    var mColorHandle: Int = -1

    val coors = floatArrayOf(
        0.0f, 0.0f, 0.0f,// (x,y,z)
        -1f, -1f, 0.0f,
        0.4f, -0.4f, 0.0f
    )
    val vertexCount = coors.size / COOR_PRE_VERTEX
    val vertexStride = COOR_PRE_VERTEX * 4

    // 颜色，rgba
    var color = floatArrayOf(0.63671875f, 0.76953125f, 0.22265625f, 1.0f)

    init {
        // 坐标数乘以 4 字节
        val bb: ByteBuffer =
            ByteBuffer.allocateDirect(coors.size * 4).order(ByteOrder.nativeOrder())
        vertexBuffer = bb.asFloatBuffer()
        vertexBuffer?.apply {
            put(coors)
            position(0)
        }

        val vertexShader = ShaderHelper.loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode)
        Log.e("-->", "vertexShader-->$vertexShader")

        val fragmentShader = ShaderHelper.loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode)
        Log.e("-->", "fragmentShader-->$fragmentShader")
        mProgram = GLES20.glCreateProgram()
        Log.e("-->", "mProgram-->$mProgram")
        GLES20.glAttachShader(mProgram!!, vertexShader)
        GLES20.glAttachShader(mProgram!!, fragmentShader)
        GLES20.glLinkProgram(mProgram!!)
        ShaderHelper.validateProgram(mProgram!!)

    }

    fun draw() {
        // 程序添加到GLES20的环境中
        GLES20.glUseProgram(mProgram!!)
        // 获取顶点着色器的vPosition成员的句柄
        mPositionHandle = GLES20.glGetAttribLocation(mProgram!!, "vPosition")
        // 启用三角形顶点的句柄
        GLES20.glEnableVertexAttribArray(mPositionHandle)
        //三角形坐标数据
        GLES20.glVertexAttribPointer(
            mPositionHandle, COOR_PRE_VERTEX,
            GLES20.GL_FLOAT, false, vertexStride, vertexBuffer
        )

        mColorHandle = GLES20.glGetUniformLocation(mProgram!!, "vColor")

        GLES20.glUniform4fv(mColorHandle, 1, color, 0)

        GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount)
        GLES20.glDisableVertexAttribArray(mPositionHandle)
    }


}